

import { AppDataSource } from '@/config/AppDataSource';
import { CreateFieldInfoDto, UpdateFieldInfoDto, QueryFieldInfoDto, DeleteFieldInfoDto, SortFieldInfoDto } from '@/dto/fieldInfo.dto';
import { FieldInfo } from '@/entities/fieldInfo.entity';
import { In } from 'typeorm';
export class FieldInfoRepository {
    private repositor = AppDataSource.getRepository(FieldInfo);
    constructor() { }

    async findExcludeId(data: UpdateFieldInfoDto) {
        const conflictCategory = await this.repositor
            .createQueryBuilder('fieldInfo')
            .where('fieldInfo.id != :id', { id: data.id })
            .andWhere('(fieldInfo.name = :name)', { name: data.name })
            .getOne();
        return conflictCategory
    }


    async fieldInfoExists(name: string) {
        const c = await this.repositor.findOne({
            where: [
                { name },
            ],
        });
        return c;
    }

    async findById(id: number) {

        const item = await this.repositor.findOneBy({
            id
        })
        return item;
    }

    async create(data: CreateFieldInfoDto): Promise<FieldInfo> {
        const fieldInfo = new FieldInfo();

        fieldInfo.status = data.status;
        fieldInfo.comment = data.comment;
        fieldInfo.code = data.code;
        fieldInfo.name = data.name;
        fieldInfo.dataType = data.dataType;
        fieldInfo.dataTypeLength = data.dataTypeLength;
        fieldInfo.isKey = data.isKey;
        fieldInfo.isNull = data.isNull;
        fieldInfo.isInsert = data.isInsert;
        fieldInfo.isEdit = data.isEdit;
        fieldInfo.isList = data.isList;
        fieldInfo.isQuery = data.isQuery;
        fieldInfo.queryType = data.queryType;
        fieldInfo.isRequired = data.isRequired;
        fieldInfo.htmlType = data.htmlType;
        // fieldInfo.parentId = data.parentId;
        fieldInfo.sortOrder = data.sortOrder;
        fieldInfo.defaultValue=data.defaultValue;

        const result = await this.repositor.save(fieldInfo)
        // console.log("result", result)
        return result;
    }
    async update(data: UpdateFieldInfoDto) {
        const fieldInfo = new FieldInfo();
        fieldInfo.id = data.id;

        fieldInfo.status = data.status;
        fieldInfo.comment = data.comment;
        fieldInfo.code = data.code!;
        fieldInfo.name = data.name!;
        fieldInfo.dataType = data.dataType!;
        fieldInfo.dataTypeLength = data.dataTypeLength;
        fieldInfo.isKey = data.isKey;
        fieldInfo.isNull = data.isNull;
        fieldInfo.isInsert = data.isInsert;
        fieldInfo.isEdit = data.isEdit;
        fieldInfo.isList = data.isList;
        fieldInfo.isQuery = data.isQuery;
        fieldInfo.queryType = data.queryType;
        fieldInfo.isRequired = data.isRequired;
        fieldInfo.htmlType = data.htmlType;
        fieldInfo.parentId = data.parentId!;
        fieldInfo.sortOrder = data.sortOrder;
        fieldInfo.defaultValue=data.defaultValue;

        return this.repositor.save(fieldInfo);

    }



    async selectList(reqData: QueryFieldInfoDto) {
        const { page, pageSize, name, orderBy, comment, status, fromDate, toDate } = reqData;

        const queryBuilder = this.repositor
            .createQueryBuilder('fieldInfo')
            .select([

                'fieldInfo.id',
                'fieldInfo.createdAt',
                'fieldInfo.updatedAt',
                'fieldInfo.status',
                'fieldInfo.comment',
                'fieldInfo.code',
                'fieldInfo.name',
                'fieldInfo.dataType',
                'fieldInfo.dataTypeLength',
                'fieldInfo.isKey',
                'fieldInfo.isNull',
                'fieldInfo.isInsert',
                'fieldInfo.isEdit',
                'fieldInfo.isList',
                'fieldInfo.isQuery',
                'fieldInfo.queryType',
                'fieldInfo.isRequired',
                'fieldInfo.htmlType',
                'fieldInfo.parentId',
                'fieldInfo.sortOrder',
                'fieldInfo.defaultValue'
            ]);

        if (name) {
            queryBuilder.andWhere('fieldInfo.name LIKE :name', { name: `%${name}%` });
        }
        if (comment) {
            queryBuilder.andWhere('fieldInfo.comment LIKE :comment', { comment: `%${comment}%` });
        }
        if (status) {
            queryBuilder.andWhere('fieldInfo.status = :status', { status });
        }
        // 添加创建日期范围查询
        if (fromDate && toDate) {
            queryBuilder.andWhere('fieldInfo.createdAt BETWEEN :fromDate AND :toDate', {
                fromDate: new Date(fromDate),
                toDate: new Date(`${toDate}T23:59:59.999Z`)

            });
        } else if (fromDate) {
            queryBuilder.andWhere('fieldInfo.createdAt >= :fromDate', {
                fromDate: new Date(fromDate)
            });
        } else if (toDate) {
            queryBuilder.andWhere('fieldInfo.createdAt <= :toDate', {
                toDate: new Date(`${toDate}T23:59:59.999Z`)

            });
        }
        const [sortBy, sortOrder] = orderBy.split(" ")
        const [fieldInfo, total] = await queryBuilder
            .orderBy(`fieldInfo.${sortBy}`, sortOrder.toLocaleUpperCase() as "ASC" | "DESC")
            .skip((page - 1) * pageSize)
            .take(pageSize)
            .getManyAndCount();
        return {
            list: fieldInfo,
            total,
            page,
            pageSize,
            totalPages: Math.ceil(total / pageSize),
        };


    }
    async delete(reqData: DeleteFieldInfoDto) {
        const result = await this.repositor.delete({
            id: In(reqData.ids)
        });
        return !!result.affected;

    }
    async sort(reqData: SortFieldInfoDto) {

        const queryRunner = AppDataSource.createQueryRunner();

        await queryRunner.connect();
        await queryRunner.startTransaction();

        try {
            for (const item of reqData.list) {
                await queryRunner.manager.update(
                    FieldInfo,
                    item.id,
                    { sortOrder: item.sortOrder }
                );
            }

            await queryRunner.commitTransaction();
            return { success: true };
        } catch (err) {
            await queryRunner.rollbackTransaction();
            throw err;
        } finally {
            await queryRunner.release();
        }
    }



    async selectByParentId(parentId: number) {

        const queryBuilder = this.repositor
            .createQueryBuilder('fieldInfo')
            .select([

                'fieldInfo.id',
                'fieldInfo.createdAt',
                'fieldInfo.updatedAt',
                'fieldInfo.status',
                'fieldInfo.comment',
                'fieldInfo.code',
                'fieldInfo.name',
                'fieldInfo.dataType',
                'fieldInfo.dataTypeLength',
                'fieldInfo.isKey',
                'fieldInfo.isNull',
                'fieldInfo.isInsert',
                'fieldInfo.isEdit',
                'fieldInfo.isList',
                'fieldInfo.isQuery',
                'fieldInfo.queryType',
                'fieldInfo.isRequired',
                'fieldInfo.htmlType',
                'fieldInfo.parentId',
                'fieldInfo.sortOrder',
                'fieldInfo.defaultValue',
            ]);

        queryBuilder.andWhere('fieldInfo.parentId = :parentId', { parentId });
        const fieldInfo = await queryBuilder
            .orderBy(`fieldInfo.id`, "ASC")

            .getMany();
        return fieldInfo;


    }
}

export default new FieldInfoRepository();

